package com.sdruixinggroup.mondayb2b.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.ui.WebActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by 00029935 on 2017/11/17.
 */

public class BindPhoneFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_identifying_code)
    EditText etIdentifyingCode;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.et_invite)
    EditText etInvite;
    @BindView(R.id.tv_send_sms)
    TextView tvSendSms;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvSendSms.setText((millisUntilFinished / 1000) + "秒后可重发");
            tvSendSms.setClickable(false);
        }

        @Override
        public void onFinish() {
            tvSendSms.setEnabled(true);
            tvSendSms.setClickable(true);
            tvSendSms.setText("获取验证码");
        }
    };

    @Override
    protected int getInflateLayout() {
        return R.layout.bind_phone_fragment;
    }

    @Override
    protected void setUpView(View view) {
        tvTitle.setText("绑定手机号");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick({R.id.ib_back, R.id.tv_next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                UserInfoUtil.saveToken(getContext(), "");
                UserInfoUtil.saveReflushToken(getContext(), "");
                getActivity().finish();
                break;
            case R.id.tv_next:

                String phone = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    showMsgToast("请输入手机号");
                    return;
                }

                String in = etIdentifyingCode.getText().toString().trim();
                if (TextUtils.isEmpty(in)) {
                    showMsgToast("请输入验证码");
                    return;
                }

                String etIite = etInvite.getText().toString().trim();
                if (TextUtils.isEmpty(etIite)) {
                    etIite = "";
                }

                bindPhone(phone, in, etIite);
                break;
        }
    }


    @OnClick(R.id.tv_send_sms)
    public void onViewClicked() {
        String phone = etPhone.getText().toString().trim();
        if (!TextUtils.isEmpty(phone)) {
            sms(phone);

        } else {
            showMsgToast("请输入手机号");
        }

    }


    private void sms(String phone) {
        String url = API.SMS_BIND_MOBILE + "?mobile=" + phone + "&access_token=" + UserInfoUtil.getInfoToken(getContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };

        OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                if (null != response) {
                    if (response.err_code == 0) {
                        showMsgToast("发送成功！");
                        restart();
                    } else {
                        showMsgToast(response.err_msg);
                    }
                }

            }
        });
    }

    private void bindPhone(String phone, String captcha, String invitation_code) {
        String url = API.MEMBER_MOBILE + "?mobile=" + phone + "&captcha=" + captcha + "&invitation_code=" + invitation_code + "&access_token=" + UserInfoUtil.getInfoToken(getContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };

        OkHttpUtils.post().url(url).headers(heades).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                if (null != response) {
                    if (response.err_code == 0) {
                        showMsgToast("绑定成功！");
                        EventBus.getDefault().post(123);
                        getActivity().finish();
                    } else {
                        showMsgToast("绑定失败!");

                    }
                }

            }
        });
    }

    /**
     * 开始倒计时
     */
    public void restart() {
        timer.start();
    }

    /**
     * 取消倒计时
     */
    public void oncancel() {
        timer.cancel();
    }

    @OnClick(R.id.tv_agreement)
    public void onClick() {
        toWebView("agreement?");
    }

    private void toWebView(String param) {
        Intent intent = new Intent(getContext(), WebActivity.class);
        intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, param);
        startActivity(intent);
    }
}
